package com.kifas.controller;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriInfo;
import javax.xml.bind.JAXBElement;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.kifas.entity.ReferenceNumberingEntity;
import com.kifas.model.xml.PersistStatus;
import com.kifas.model.xml.ReferenceNumberingModel;
import com.kifas.service.EntityServiceManager;

/**
 * @author brainmaster
 * 
 */

@Component
@Scope("prototype")
@Path("/ReferenceNumber")
public class ReferenceNumberingController {

	private static Logger log = Logger
			.getLogger(ReferenceNumberingController.class);

	@Context
	UriInfo uriInfo;

	@Autowired
	private EntityServiceManager entityManager;

	@GET
	@Produces(MediaType.TEXT_XML)
	public ReferenceNumberingModel getReferenceNumber(
			@QueryParam("unit") Integer unit,
			@QueryParam("prefix") String prefix) {
		ReferenceNumberingModel model = new ReferenceNumberingModel();
		model.setResult(entityManager.getReference(unit, prefix));
		return model;
	}

	@POST
	@Consumes(MediaType.APPLICATION_XML)
	@Produces(MediaType.APPLICATION_XML)
	public PersistStatus insertNewReference(
			JAXBElement<ReferenceNumberingModel> xml) {
		ReferenceNumberingModel model = xml.getValue();
		ReferenceNumberingEntity reference = new ReferenceNumberingEntity(null,
				model.getKeterangan(), model.getUnit(), model.getPrefix(),
				model.getSeq());
		try {
			entityManager.persist(reference);
		} catch (Exception e) {
			log.error("can not persist reference numbering", e);
			return new PersistStatus("ReferenceNumberingEntity", "failed",
					"can not persist reference numbering");
		}
		return new PersistStatus("ReferenceNumberingEntity", "success");
	}
}
